import asyncio
import httpx
from fastapi import HTTPException
from tenacity import retry, stop_after_attempt, wait_fixed


@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))
async def get_chat_tts_model(answer: str):
    EXTERNAL_API_URL = "http://192.168.124.32:9966/generate_voice"
    payload = {
        "text": answer,
        "prompt": "",
        "voice": 3333,  # 修改为整数类型以匹配服务端期望的参数类型
        "temperature": 0.3,
        "top_p": 0.7,
        "top_k": 20,
        "skip_refine": 0,
        "custom_voice": 0
    }

    try:
        async with httpx.AsyncClient(timeout=10000.0, trust_env=False) as client:
            response = await client.post(EXTERNAL_API_URL, data=payload)
            data = response.json()
            url = data.get('url')
            if not url:
                raise HTTPException(status_code=500, detail="TTS 接口未返回音频 URL")

            # 2. 下载该 URL 指向的 .wav 文件
            voice_response = await client.get(url)
            voice_response.raise_for_status()

            # 3. 返回二进制内容
            return voice_response.content

    except httpx.HTTPStatusError as e:
        raise HTTPException(status_code=e.response.status_code, detail="API 请求失败")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# asyncio.run(get_chat_tts_model("八百标兵奔被迫"))